<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <div class="title">
      <el-tag>操作步骤说明：</el-tag>
      <el-tag>第一步：点击新增，填写用能预算申请表</el-tag>
      <el-tag>第二步：点击本页面上报按钮，进行上报</el-tag>
      <el-tag type="danger"
        >注：上报后发现数据错误，①上级部门没有审核可以点击撤回按钮调整，②如已审核点击纠正按钮调整，③如已汇总则无法再调整</el-tag
      >
    </div>
    <lb-table
      class="mt20"
      :column="tableData.column"
      :data="tableData.data"
      :height="600"
      border
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import auth from "@/plugins/auth";
import {
  list,
  auditBudgetDeclaration,
  deletebudgetDeclare,
} from "@/api/work/budgetDeclaration.js";
import { formatDate } from "@/utils/index";
import operate from "@/views/work/budgetDeclaration/components/operate.vue";
import detail from "@/views/work/budgetDeclaration/components/detail.vue";
export default {
  name: "budgetDeclaration",
  dicts: [
    "energy_declare_type",
    "energy_identify_types",
    "energy_budget_declare_status",
  ],
  components: {
    operate,
    detail,
  },
  data() {
    return {
      //弹窗
      id: "",
      modelName: "",
      show: false,
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            /* 时间日期选择器 */
            year: {
              label: "年份:",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              placeholder: "请选择年份",
              "value-format": "yyyy",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              plain: true,
              display: true,
              size: "small",
              icon: "el-icon-plus",
              click: () => this.showModel("operate"),
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "sysDeptName",
            label: "单位名称",
            minWidth: 200,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "yearStr",
            label: "用能预算利用时间",
            width: 150,
            align: "center",
            showOverflowTooltip: true,
          },
          // {
          //   prop: "declareType",
          //   label: "填报类型",
          //   width: 100,
          //   align: "center",
          //   showOverflowTooltip: true,
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.energy_declare_type}
          //           value={scope.row.declareType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          {
            prop: "inputTime",
            label: "填表时间",
            width: 200,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "inputUserName",
            label: "录入人员",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "declareTime",
            label: "上报时间",
            width: 200,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "updateTime",
            label: "更新时间",
            width: 200,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "status",
            label: "状态",
            width: 200,
            align: "center",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.energy_budget_declare_status}
                    value={scope.row.status}
                  />
                </div>
              );
            },
          },
          {
            prop: "reason",
            label: "备注",
            align: "center",
            showOverflowTooltip: true,
          },

          {
            label: "操作",
            width: "300",
            fixed: "right",
            render: (h, scope) => {
              let a, b, c, d, e;
              if ([0, -1, -2].includes(scope.row.status)) {
                if (auth.hasPermi("energy:budget-declare:audit:1")) {
                  a = (
                    <el-button
                      v-hasPermi={["energy:budget-declare:audit:1"]}
                      type="text"
                      size="small"
                      icon="el-icon-upload2"
                      onClick={() => {
                        this.handleUp(scope.row, 1);
                      }}
                    >
                      上报
                    </el-button>
                  );
                }
                if (auth.hasPermi("energy:budget-declare:modify")) {
                  d = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-edit"
                      onClick={() => {
                        this.showModel("operate", scope.row);
                      }}
                    >
                      编辑
                    </el-button>
                  );
                }
                if (auth.hasPermi("energy:budget-declare:delete")) {
                  e = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-delete"
                      onClick={() => {
                        this.handleDelete(scope.row);
                      }}
                      class="text-danger"
                    >
                      删除
                    </el-button>
                  );
                }
              } else {
                a = <span></span>;
                d = <span></span>;
                e = <span></span>;
              }
              if (
                scope.row.status == 1 &&
                auth.hasPermi("energy:budget-declare:audit:2")
              ) {
                b = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-brush"
                    onClick={() => {
                      this.handleUp(scope.row, 2);
                    }}
                  >
                    撤回
                  </el-button>
                );
              } else {
                b = <span></span>;
              }
              if (
                [2, 3, 4, 5].includes(scope.row.status) &&
                !scope.row.isCorrectData &&
                auth.hasPermi("energy:budget-declare:audit:3")
              ) {
                c = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-upload2"
                    onClick={() => {
                      this.handleUp(scope.row, 3);
                    }}
                  >
                    纠正
                  </el-button>
                );
              } else {
                c = <span></span>;
              }
              return (
                <div>
                  {a}
                  {d}
                  {e}
                  {b}
                  {c}
                  {
                    <el-button
                      v-hasPermi={["energy:budget-declare:detail"]}
                      type="text"
                      size="small"
                      icon="el-icon-view"
                      onClick={() => {
                        this.showModel("detail", scope.row);
                      }}
                    >
                      详情
                    </el-button>
                  }
                </div>
              );
            },
          },
        ],
        data: [],
      },
    };
  },
  mounted() {
    this.judgePermi();
    this.handlerSearchDetail();
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("energy:budget-declare:add")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!错误码309001");
        });
    },
    // 搜索
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
        orderByColumn: "ebd.createTime",
        isAsc: "desc",
      };
      this.initData(currentPage, this.pageSize, data);
    },
    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const that = this;
      that.$modal
        .confirm("是否确认删除此数据项？")
        .then(function () {
          deletebudgetDeclare(row.id)
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.handlerSearchDetail();
              that.$modal.msgSuccess("删除成功");
            })
            .catch(() => {
              // this.$message.error("系统错误,请联系管理员!错误码309006");
            });
        })
        .catch(() => {});
    },
    // 上报
    handleUp(row, type) {
      const that = this;
      let text = "";
      if (type == 1) {
        text = "上报";
      } else if (type == 2) {
        text = "撤回";
      } else if (type == 3) {
        text = "纠正";
      }
      that
        .$confirm(`确认${text}吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let day = formatDate(new Date(), "yyyy-MM-dd");
          auditBudgetDeclaration({
            eventType: type,
            declareId: row.id,
            eventTime: day,
          })
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.$message({
                type: "success",
                message: "操作成功!",
              });
              that.handlerSearchDetail();
            })
            .catch((err) => {
              // this.$message.error("系统错误,请联系管理员!错误码309005");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .title {
  .el-tag {
    margin-right: 10px !important;
  }
}
</style>
